package com.uobgroup.ews.uam.core.dao;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import com.uobgroup.ews.uam.core.domain.BaseEntity;

public abstract class AbstractJpaDao<T> implements GenericDao<T> {

   private Class<T> clazz;

   @PersistenceContext
   EntityManager entityManager;

   public void setClazz(final Class<T> clazzToSet) {
      this.clazz = clazzToSet;
   }

   public T findOne(final Long id) {
      return entityManager.find(clazz, id);
   }

   @SuppressWarnings("unchecked")
   public List<T> findAll() {
      return entityManager.createQuery("from " + clazz.getName()).getResultList();
   }

   public void save(final T entity) {
      entityManager.persist(entity);
   }

   public T update(final T entity) {
      return entityManager.merge(entity);
   }

   public void delete(final T entity) {
      entityManager.remove(entity);
   }

   public void deleteById(final Long entityId) {
      final T entity = findOne(entityId);
      delete(entity);
   }
   
   public void flush() {
      entityManager.flush();
   }
   
   public void updateUserIdAndDelete(Class<?> clazz, Long id, String userId){
      Object entity = entityManager.find(clazz, id);
      if(entity instanceof BaseEntity){
         ((BaseEntity)entity).setLastModificationUserId(userId);
         entity = entityManager.merge(entity);
         entityManager.remove(entity);
      }
   }
}
